<template>
  <div>
    <div class="search">
      <span>文章标题</span>
      <el-input
        style="width: 220px"
        v-model="params.categoryName"
        placeholder="请输入(模糊查询)"
      ></el-input>
      <span>发布日期</span>
      <el-date-picker
        v-model="value"
        type="daterange"
        align="right"
        unlink-panels
        value-format="yyyy-MM-dd 00:00:00"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
      >
      </el-date-picker>
      <span></span>
      <el-button type="primary" @click="search"
        ><i class="el-icon-search"> 查询</i></el-button
      >
      <span></span
      ><el-button @click="reset"
        ><i class="el-icon-refresh-right"> 重置</i></el-button
      >
    </div>
    <div class="body">
      <div class="addtext">
        <el-button type="primary" @click="resetForm"
          ><i class="el-icon-plus"> 新增</i></el-button
        >
        <!-- 需要补充表单 -->
        <el-dialog title="新增分类" :visible.sync="dialogFormVisible">
          <el-form :model="addname" :rules="rules" ref="addname">
            <el-form-item label="分类名称" prop="name">
              <el-input
                v-model="addname.name"
                autocomplete="off"
                maxlength="10"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </div>
        </el-dialog>
        <!--  -->
      </div>
      <div class="showbox" style="line-height: 0">
        <el-table :data="datalist" style="width: 100%" stripe>
          <el-table-column label="分类名称" width="180" prop="name">
          </el-table-column>
          <el-table-column label="创建事件" width="180" prop="createTime">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                ><i>删除</i></el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.current"
          :page-sizes="[10, 20, 50]"
          :page-size="params.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { classify, classifyDelete, classifyAdd } from "../../../../units/htapi";
export default {
  data() {
    var name = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("名称不能为空"));
      } else {
        callback();
      }
    };
    return {
      params: {
        current: 1, //页面号
        size: 10, //页面显示条数
        categoryName: "", //搜索值
        startDate: "", //开始时间
        endDate: "", //结束时间
      },
      rules: {
        name: [{ required: true, validator: name, trigger: "blur" }],
      },
      addname: {
        name: "",
      },
      dialogFormVisible: false,
      count: 0, //总页数
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      }, //日期选择器

      value: "",
      datalist: [], //存储渲染数据的列表
    };
  },
  created() {
    this.getdata();
  },
  methods: {
    async getdata() {
      this.loading = true;
      try {
        let res = await classify(this.params);
        // console.log(res);
        this.datalist = res.data.data; //传入数据列表
        this.count = res.data.total; //传入数据条数
      } catch (error) {
        this.$message.error("数据加载失败");
        // console.log(error, "这是一个错误");
      } finally {
        this.loading = false; // 无论成功失败都关闭loading
      }
    },

    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await classifyDelete({ categoryId: row.id });
            this.getdata();
            this.$message.success("删除成功");
          } catch (error) {
            console.log("删除出错", error);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //   console.log(index, row);
    //删除按钮

    search() {
      if (this.value && this.value.length === 2) {
        this.params.startDate = this.value[0];
        this.params.endDate = this.value[1] || this.value[0]; // 处理结束日期为空的情况
      } else {
        this.params.startDate = "";
        this.params.endDate = "";
      }

      this.getdata(); //重新获取数据
    },
    reset() {
      // 重置按钮
      this.params = {
        current: 1,
        size: 10,
        categoryName: "",
        startDate: "",
        endDate: "",
      };
      this.value = ""; // 重置日期选择器
      this.getdata();
    },
    handleSizeChange(val) {
      //分页器
      this.params.size = val;
      // console.log(`每页 ${val} 条`);
      this.params.current = 1; // 切换每页条数时，重置到第一页
      this.getdata(); // 重新加载数据
    },
    handleCurrentChange(val) {
      this.params.current = val;
      // console.log(`当前页: ${val}`);
      this.getdata(); // 重新加载数据
    },

    submitForm() {
      this.$refs["addname"].validate(async (valid) => {
        if (valid) {
          try {
            // 假设新增分类的接口为 classifyAdd（需从htapi导入）
            await classifyAdd(this.addname); // 调用新增接口，传递分类名称
            this.$message.success("添加成功");
            this.dialogFormVisible = false;
            this.getdata(); // 新增成功后刷新列表
            this.addname.name = ""; // 清空表单
          } catch (error) {
            this.$message.error(
              "添加失败：" + (error.response?.data?.msg || "网络错误")
            );
          }

          this.$message.success("添加成功");
          this.dialogFormVisible = false;
        } else {
          this.$message.error("添加失败");
          this.dialogFormVisible = false;
          return false;
        }
      });
    },
    resetForm() {
      this.dialogFormVisible = true;

      this.$nextTick(() => {
        // 等待DOM更新后再重置
        if (this.$refs["addname"]) {
          this.$refs["addname"].resetFields();
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.search {
  width: 100%;
  height: 80px;
  background-color: #fff;
  margin-bottom: 20px;
  line-height: 20px;
  text-align: left;
  box-sizing: border-box;
  padding: 20px;
  .el-button {
    margin-left: 10px; // 给按钮添加左侧间距
  }
  span {
    margin-left: 20px;
    margin-right: 10px;
  }
}
.body {
  width: 100%;
  height: auto;
  min-height: 200px;
  background-color: #fff;
  box-sizing: border-box;
  padding: 20px;
  .addtext {
    line-height: 20px;
    width: 100%;
    height: 40px;
    text-align: left;
    box-sizing: border-box;
    // background-color: red;
    margin-bottom: 20px;
  }
  .showbox {
    // width: 100%;
    // height: 500px;
    // background-color: red;
    img {
      width: 50px;
      height: 50px;
    }
  }
  .page {
    margin-top: 20px;
  }
}
</style>